-- kill_boss
-- Created by chengb Sep/11/2015
-- 成就：击杀boss

-- 内部函数声明
local whenBossDie;

-- 关注获得物品的事件
EventMgr.register("game_achievement/kill_boss", event.BOSS_DIE, function(args)
    whenBossDie(args);
end);

-- 注册击杀boss的回调
whenBossDie = function(args)
    local monster = args.monster;

    if not monster then
        return;
    end

    local classId = monster:query("base_class_id");

    -- 如果是小boss，忽略不计
    local dbase = MonsterM.query(classId, "dbase");
    if 1 == dbase["child_boss"] then
        return;
    end

    -- 玩家不在迷宫中
    if not DungeonM.isInDungeon() then
        return;
    end

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];

        -- 目前需求怪物编号支持两种格式的配置：1.整型      2.数组
        if type(ruleArg["class_id"]) == 'number' and
            ruleArg["class_id"] ~= classId then
            return false;
        end

        if type(ruleArg["class_id"]) == 'table' and
            table.indexOf(ruleArg["class_id"], classId) == -1 then
            return false;
        end

        if type(ruleArg["round"]) == 'number' and
           CombatM.getRound() > ruleArg["round"] then
            -- 回合数不达标
            return false;
        end

        return true;
    end

    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("kill_boss");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg  = config["rule_arg"];
        local round    = ruleArg["round"];
        local progress = config["progress"];
        local desc     = config["desc"];

        desc = string.gsub(desc, "{0}", progress);
        if round ~= nil then
            desc = string.gsub(desc, "{round}", round);
        end

        return desc;
    end,
};